
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Token：服务端身份验证的流行方案 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,身份认证服务端提供资源给客户端，但是某些资源是有条件的。所以服务端要能够识别请求者的身份，然后再判断所请求的资源是否可以给请求者。
token是一种身份验证的机制，初始时用户提交账号数据给服务端，服,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">Token：服务端身份验证的流行方案</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="javascript:;"><b>「 </b>Article<b> 」</b></a>
                
                May 23, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/05/23/study/Token%EF%BC%9A%E6%9C%8D%E5%8A%A1%E7%AB%AF%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81%E7%9A%84%E6%B5%81%E8%A1%8C%E6%96%B9%E6%A1%88/" title="Token：服务端身份验证的流行方案" class="">Token：服务端身份验证的流行方案</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    21k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    19 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Token/" rel="tag">Token</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="身份认证"><a href="#身份认证" class="headerlink" title="身份认证"></a>身份认证</h1><p>服务端提供资源给客户端，但是某些资源是有条件的。所以服务端要能够识别请求者的身份，然后再判断所请求的资源是否可以给请求者。</p>
<p>token是一种身份验证的机制，初始时用户提交账号数据给服务端，服务端采用一定的策略生成一个字符串（token），token字符串中包含了少量的用户信息，并且有一定的期限。服务端会把token字符串传给客户端，客户端保存token字符串，并在接下来的请求中带上这个字符串。</p>
<p>它的工作流程大概是这样</p>
<h2 id="Token机制"><a href="#Token机制" class="headerlink" title="Token机制"></a>Token机制</h2><blockquote>
<p>在这样的流程下，我们需要考虑下面几个问题：</p>
<ul>
<li>如何根据token获取用户的信息？</li>
<li>确保识别伪造的token？</li>
<li>这里是指token不是经过服务端来生成的。</li>
<li>如何应付冒充的情况？</li>
<li>非法客户端拦截了合法客户端的token，然后使用这个token向服务端发送请求，冒充合法客户端。</li>
</ul>
</blockquote>
<h2 id="用户匹配"><a href="#用户匹配" class="headerlink" title="用户匹配"></a>用户匹配</h2><p>服务端在生成token时，加入少量的用户信息，比如用户的id。服务端接收到token之后，可以解析出这些数据，从而将token和用户关联了起来。</p>
<h2 id="防伪造"><a href="#防伪造" class="headerlink" title="防伪造"></a>防伪造</h2><p>一般情况下，建议放入token的数据是不敏感的数据，这样只要服务端使用私钥对数据生成签名，然后和数据拼接起来，作为token的一部分即可。比如JWT，参考JSON Web Token - 在Web应用间安全地传递信息。</p>
<p>在我知道JWT之前，我先了解的是另一种模式。基于加密的算法，对数据进行加密，把加密的结果作为token（<code>http://blog.leapoahead.com/2015/09/06/understanding-jwt/</code>）。</p>
<p>本文主要讨论后一种模式。</p>
<h2 id="防冒充"><a href="#防冒充" class="headerlink" title="防冒充"></a>防冒充</h2><h3 id="加干扰码"><a href="#加干扰码" class="headerlink" title="加干扰码"></a>加干扰码</h3><p>服务端在生成token时，使用了客户端的UA作为干扰码对数据加密，客户端进行请求时，会同时传入token、UA，服务端使用UA对token解密，从而验证用户的身份。<br><a id="more"></a><br>如果只是把token拷贝到另一个客户端使用，不同的UA会导致在服务端解析token失败，从而实现了一定程度的防冒充。但是攻击者如果猜到服务端使用UA作为加密钥，他可以修改自己的UA。</p>
<h3 id="有效期"><a href="#有效期" class="headerlink" title="有效期"></a>有效期</h3><p>给token加上有效期，即使被冒充也只是在一定的时间段内有效。这不是完美的防御措施，只是尽量减少损失。</p>
<p>服务端在生成token时，加入有效期。每次服务端接收到请求，解析token之后，判断是否已过期，如果过期就拒绝服务。</p>
<h3 id="token刷新"><a href="#token刷新" class="headerlink" title="token刷新"></a>token刷新</h3><p>如果token过期了，客户端应该对token续期或者重新生成token。</p>
<blockquote>
<p>这取决于token的过期机制。<br>服务器缓存token及对应的过期时间<br>这个时候就可以采用续期的方式，服务器更新过期时间，token再次有效。<br>token中含有过期时间<br>这个时候需要重新生成token。</p>
</blockquote>
<p>在token续期或者重新生成token的时候，需要额外加入数据来验证身份。因为token已经过期了，即token已经不能用来验证用户的身份了。这个时候可以请求用户重新输入账号和密码，但是用户体验稍差。</p>
<p>另一种方式是使用摘要。服务端生成token，同时生成token的摘要，然后一起返回给客户端。客户端保存摘要，一般请求只需要用到token，在刷新token时，才需要用到摘要。服务端验证摘要，来验证用户的身份。因为摘要不会频繁的在客户端和服务端之间传输，所以被截取的概率较小。</p>
<h2 id="Token工作流程"><a href="#Token工作流程" class="headerlink" title="Token工作流程"></a>Token工作流程</h2><h3 id="生成token"><a href="#生成token" class="headerlink" title="生成token"></a>生成token</h3><p>一般在登录的时候生成token。Token管理者负责根据用户的数据生成token和摘要，摘要用来给APP端刷新token用，类似于微信登录中的refresh_token。</p>
<p>生成token的过程中，ua的充作干扰码。没有相同的ua，就无法解析生成的token字符串。如果客户端是混合开发的模式，生成token和使用token的代理可能不同（比如一个是h5，一个是原生），ua就会不同，token就无法成功的使用。可以选择其他的客户端数据作为干扰码，</p>
<blockquote>
<p>注意考虑下面的问题：</p>
<ul>
<li>不同的客户端，干扰码应该不同</li>
<li>干扰码的很大一个作用是防冒充，如果选择的充当干扰码的客户端数据没有区分性，就达不到效果。选择充当干扰码的数据，在哪些情况下会变化？这些情况是否合理？</li>
<li>比如干扰码数据中含有app的版本号，那么app版本升级就会导致干扰码变化。服务端根据新的干扰码，无法解析旧的token，此时用户必须重新登录。这种情况是合理的吗？如果不合理，干扰码中就不应该含有app的版本号。</li>
</ul>
</blockquote>
<h3 id="拦截验证"><a href="#拦截验证" class="headerlink" title="拦截验证"></a>拦截验证</h3><p>客户端的每一次请求，都必须携带token、ua，拦截器会对敏感资源的访问进行拦截，然后根据ua解析token，解析不成功，表示token和ua不匹配。解析成功之后，判断token是否已过期，如果是，拒绝服务。所有都ok的情况下，拦截器放行，请求传达到业务服务者。</p>
<h3 id="Token刷新"><a href="#Token刷新" class="headerlink" title="Token刷新"></a>Token刷新</h3><p>当token过期，用户需要刷新token。刷新token本质上是这样的：</p>
<p>客户端需要把token、摘要、ua都传给服务端，服务端对token重新生成摘要，通过判断两个摘要是否相同来验证这次请求刷新token的客户端，是不是上次请求生成token的客户端。验证通过，服务端需要使用用户数据重新生成token，用户数据则来自用ua解析token的结果。</p>
<h2 id="HTML-amp-JS等前端知识系列之Ajax-post请求带有token向Django请求"><a href="#HTML-amp-JS等前端知识系列之Ajax-post请求带有token向Django请求" class="headerlink" title="HTML&amp;JS等前端知识系列之Ajax post请求带有token向Django请求"></a>HTML&amp;JS等前端知识系列之Ajax post请求带有token向Django请求</h2><p>我们 在母板上写入这段代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">&lt;script type=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line">        <span class="comment">// 个人定义大函数，不是重点，可以忽略</span></span><br><span class="line">        $(<span class="built_in">document</span>).ready(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            get_sys_load();</span><br><span class="line">            <span class="keyword">var</span> csrftoken = getCookie(<span class="string">'csrftoken'</span>);</span><br><span class="line">            <span class="keyword">var</span> active_node = $(<span class="string">"#mainnav-menu a[href='&#123;&#123; request.path &#125;&#125;']"</span>);</span><br><span class="line">            active_node.parent().addClass(<span class="string">"active-link"</span>);</span><br><span class="line">            <span class="keyword">if</span> (active_node.parent().parent().hasClass(<span class="string">"collapse"</span>))&#123;</span><br><span class="line">                active_node.parent().parent().addClass(<span class="string">"in"</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;);<span class="comment">//end doc ready</span></span><br><span class="line">        <span class="comment">// 个人定义大函数，不是重点，可以忽略</span></span><br><span class="line">        <span class="function"><span class="keyword">function</span>  <span class="title">get_sys_load</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            $.ajax(&#123;</span><br><span class="line">                url: <span class="string">"&#123;% url 'get_server_host_status' %&#125;"</span>,</span><br><span class="line">                type: <span class="string">"GET"</span>,</span><br><span class="line">                dataType: <span class="string">"json"</span>,</span><br><span class="line">                success: <span class="function"><span class="keyword">function</span>(<span class="params">callback</span>)</span>&#123;</span><br><span class="line">                    <span class="keyword">for</span>( i <span class="keyword">in</span> callback)&#123;</span><br><span class="line">                            <span class="built_in">console</span>.log(i,callback[i]);</span><br><span class="line">                            $(<span class="string">'#'</span>+ i +<span class="string">'_display'</span>).text(callback[i]);</span><br><span class="line">                            $(<span class="string">'#'</span>+ i +<span class="string">'_width'</span>).text(callback[i]);</span><br><span class="line">                            $(<span class="string">'#'</span>+ i +<span class="string">'_attr'</span>).css(<span class="string">'width'</span>,callback[i]+<span class="string">'%'</span>)</span><br><span class="line"></span><br><span class="line">                    &#125;<span class="comment">// end for</span></span><br><span class="line">                &#125;,<span class="comment">// end sucess func</span></span><br><span class="line">                error: <span class="function"><span class="keyword">function</span>(<span class="params">callback</span>)</span>&#123;</span><br><span class="line">                    alert(callback)</span><br><span class="line">                &#125;<span class="comment">// end error func</span></span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 这个才是重点的代码，必须写</span></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">getCookie</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> cookieValue = <span class="literal">null</span>;</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">document</span>.cookie &amp;&amp; <span class="built_in">document</span>.cookie !== <span class="string">''</span>) &#123;</span><br><span class="line">                <span class="keyword">var</span> cookies = <span class="built_in">document</span>.cookie.split(<span class="string">';'</span>);</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; cookies.length; i++) &#123;</span><br><span class="line">                    <span class="keyword">var</span> cookie = jQuery.trim(cookies[i]);</span><br><span class="line">                    <span class="comment">// Does this cookie string begin with the name we want?</span></span><br><span class="line">                    <span class="keyword">if</span> (cookie.substring(<span class="number">0</span>, name.length + <span class="number">1</span>) === (name + <span class="string">'='</span>)) &#123;</span><br><span class="line">                        cookieValue = <span class="built_in">decodeURIComponent</span>(cookie.substring(name.length + <span class="number">1</span>));</span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> cookieValue;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 这个才是重点的代码，必须写</span></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">csrfSafeMethod</span>(<span class="params">method</span>) </span>&#123;</span><br><span class="line">            <span class="comment">// these HTTP methods do not require CSRF protection</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="regexp">/^(GET|HEAD|OPTIONS|TRACE)$/</span>.test(method));</span><br><span class="line">        &#125;</span><br><span class="line">        $.ajaxSetup(&#123;</span><br><span class="line">            beforeSend: <span class="function"><span class="keyword">function</span>(<span class="params">xhr, settings</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">if</span> (!csrfSafeMethod(settings.type) &amp;&amp; !<span class="keyword">this</span>.crossDomain) &#123;</span><br><span class="line">                    xhr.setRequestHeader(<span class="string">"X-CSRFToken"</span>, csrftoken);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">    &#123;% block  bottom-js %&#125;</span></span><br><span class="line"><span class="regexp">    &#123;% endblock %&#125;</span></span><br></pre></td></tr></table></figure>
<p>我们在子板上调用这端js代码，调用的前提是子板的html页面必须嵌套了这个 csrf_token, 代码如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">html页面的代码：</span><br><span class="line">==================</span><br><span class="line">&lt;span&gt;&#123;% csrf_token %&#125;&lt;<span class="regexp">/span&gt;</span></span><br><span class="line"><span class="regexp">==================</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">======JQuery代码 =======</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">&#123;% block  bottom-js %&#125;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">    function run_cmd()&#123;</span></span><br><span class="line"><span class="regexp">        var csrftoken = getCookie('csrftoken');     /</span><span class="regexp">/ 调用获取token的方法来获取token，getCookie是前面定义好的函数。</span></span><br><span class="line"><span class="regexp">        var input_cmd = $('textarea').val();</span></span><br><span class="line"><span class="regexp">        $.ajax(&#123;</span></span><br><span class="line"><span class="regexp">            url:"&#123;% url 'put_cmd' %&#125;",</span></span><br><span class="line"><span class="regexp">            type:'POST',</span></span><br><span class="line"><span class="regexp">            dataType:'json',</span></span><br><span class="line"><span class="regexp">            token: csrftoken,                  /</span><span class="regexp">/ 把token塞入头部</span></span><br><span class="line"><span class="regexp">            data:&#123;'host_id':$('#host_id').text(),'minion_name':$('#minion_id').text(),'cmd':input_cmd&#125;,</span></span><br><span class="line"><span class="regexp">            success: function(callback)&#123;</span></span><br><span class="line"><span class="regexp">                console.log(callback)</span></span><br><span class="line"><span class="regexp">            &#125;, /</span><span class="regexp">/ end success</span></span><br><span class="line"><span class="regexp">            error: function (callback) &#123;</span></span><br><span class="line"><span class="regexp">                console.log(callback);</span></span><br><span class="line"><span class="regexp">                $('code').append(callback)</span></span><br><span class="line"><span class="regexp">            &#125;</span></span><br><span class="line"><span class="regexp">        &#125;)</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">    function show_result(content)&#123;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">&lt;/</span>script&gt;</span><br><span class="line"></span><br><span class="line">&#123;% endblock %&#125;</span><br></pre></td></tr></table></figure>
<p>此时，我们在提交post请求，就能够正常提交了，可以参考官网的信息：<br><a href="https://docs.djangoproject.com/en/dev/ref/csrf/#ajax" target="_blank" rel="noopener">ajax token</a>。</p>
<h2 id="登录后保存token到cookie中"><a href="#登录后保存token到cookie中" class="headerlink" title="登录后保存token到cookie中"></a>登录后保存token到cookie中</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.引入相应JS</span></span><br><span class="line"></span><br><span class="line">　　&lt;script src=<span class="string">"web/js/jquery-1.9.1.min.js"</span>&gt;&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">　　&lt;script src="web/</span>js/jquery.cookie.js<span class="string">"&gt;&lt;/script&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 2.保存cookie</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　$.cookie("</span>名称<span class="string">","</span>值<span class="string">") //$.cookie('cookieName', 'cookieValue');</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　$.cookie("</span>名称<span class="string">","</span>值<span class="string">",&#123;expires:失效时间&#125;)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 3.获取cookie</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　$.cookie("</span>名称<span class="string">") //$.cookie('cookieName');</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 4.删除cookie</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　$.cookie("</span>名称<span class="string">",null)</span></span><br></pre></td></tr></table></figure>
<h2 id="Token机制相比Cookie机制的优点"><a href="#Token机制相比Cookie机制的优点" class="headerlink" title="Token机制相比Cookie机制的优点"></a>Token机制相比Cookie机制的优点</h2><ul>
<li><p><strong>支持跨域访问:</strong>cookie是不允许跨域访问的，这一点对token机制是不存在的，前提是传输的用户认证信息通过HTTP头传输.</p>
</li>
<li><p><strong>无状态(也称：服务端可扩展行):</strong>Token机制在服务端不需要存储session信息，因为Token 自身包含了所有登录用户的信息，只需要在客户端的cookie或本地介质存储状态信息.</p>
</li>
<li><p><strong>更适用于cdn:</strong> 可以通过内容分发网络请求你服务端的所有资料（如：javascript，HTML,图片等），而你的服务端只要提供API即可</p>
</li>
<li><p><strong>去耦</strong>: 不需要绑定到一个特定的身份验证方案。Token可以在任何地方生成，只要在你的API被调用的时候，你可以进行Token生成调用即可.</p>
</li>
<li><p><strong>更适用于移动应用:</strong> 当你的客户端是一个原生平台（iOS, Android，Windows 8等）时，Cookie是不被支持的（你需要通过Cookie容器进行处理），这时采用Token认证机制就会简单得多。</p>
</li>
<li><p><strong>CSRF</strong>:因为不再依赖于Cookie，所以你就不需要考虑对CSRF（跨站请求伪造）的防范。</p>
</li>
<li><p><strong>性能:</strong> 一次网络往返时间（通过数据库查询session信息）总比做一次HMACSHA256计算 的Token验证和解析要费时得多.不需要为登录页面做特殊处理: 如果你使用Protractor 做功能测试的时候，不再需要为登录页面做特殊处理.</p>
</li>
<li><p><strong>基于标准化:</strong>你的API可以采用标准化的 JSON Web Token (JWT). 这个标准已经存在多个后端库（.NET, Ruby, Java,Python, PHP）和多家公司的支持（如：Firebase,Google, Microsoft）.</p>
</li>
</ul>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#身份认证"><span class="toc-number">1.</span> <span class="toc-text">身份认证</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Token机制"><span class="toc-number">1.1.</span> <span class="toc-text">Token机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#用户匹配"><span class="toc-number">1.2.</span> <span class="toc-text">用户匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#防伪造"><span class="toc-number">1.3.</span> <span class="toc-text">防伪造</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#防冒充"><span class="toc-number">1.4.</span> <span class="toc-text">防冒充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#加干扰码"><span class="toc-number">1.4.1.</span> <span class="toc-text">加干扰码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#有效期"><span class="toc-number">1.4.2.</span> <span class="toc-text">有效期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#token刷新"><span class="toc-number">1.4.3.</span> <span class="toc-text">token刷新</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Token工作流程"><span class="toc-number">1.5.</span> <span class="toc-text">Token工作流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#生成token"><span class="toc-number">1.5.1.</span> <span class="toc-text">生成token</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#拦截验证"><span class="toc-number">1.5.2.</span> <span class="toc-text">拦截验证</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Token刷新"><span class="toc-number">1.5.3.</span> <span class="toc-text">Token刷新</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#HTML-amp-JS等前端知识系列之Ajax-post请求带有token向Django请求"><span class="toc-number">1.6.</span> <span class="toc-text">HTML&amp;JS等前端知识系列之Ajax post请求带有token向Django请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#登录后保存token到cookie中"><span class="toc-number">1.7.</span> <span class="toc-text">登录后保存token到cookie中</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Token机制相比Cookie机制的优点"><span class="toc-number">1.8.</span> <span class="toc-text">Token机制相比Cookie机制的优点</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
